<template>
  <div>
    <h2>标签管理</h2>

    <el-table :data="tags" border style="width: 100%">
      <el-table-column prop="name" label="标签名称" />
      <el-table-column label="操作" width="240">
        <template #default="{ row }">
          <el-button size="small" @click="editTag(row)">修改</el-button>
          <el-button size="small" type="danger" @click="confirmDelete(row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <el-button type="primary" class="mt-4" @click="createTag">新建标签</el-button>

    <el-dialog
      v-model="dialogVisible"
      :title="isEditing ? '修改标签' : '新建标签'"
      width="400px"
      :lock-scroll="false"
    >
      <el-input v-model="inputName" placeholder="请输入标签名称" />

      <template #footer>
        <el-button @click="dialogVisible = false">取消</el-button>
        <el-button type="primary" @click="handleDialogConfirm">确定</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted,watch } from 'vue'
import { ElMessageBox, ElMessage } from 'element-plus'
import {
  getAllTags,
  createTagRequest,
  updateTagRequest,
  deleteTagRequest
} from '@/api/tag'

interface Tag {
  id: number
  name: string
}

const tags = ref<Tag[]>([])
const dialogVisible = ref(false)
const inputName = ref('')
const isEditing = ref(false)
const currentEditingTag = ref<Tag | null>(null)

onMounted(loadTags)

async function loadTags() {
  try {
    const res = await getAllTags()
    if (res.code === 0 && Array.isArray(res.data)) {
      tags.value = res.data
      console.log('加载的标签数据:', tags.value)
    } else {
      ElMessage.error(res.message || '获取标签失败')
    }
  } catch (err) {
    console.error('请求标签接口失败', err)
    ElMessage.error('请求标签接口失败')
  }
}

function createTag() {
  inputName.value = ''
  isEditing.value = false
  currentEditingTag.value = null
  dialogVisible.value = true
}

function editTag(tag: Tag) {
  inputName.value = tag.name
  isEditing.value = true
  currentEditingTag.value = tag
  dialogVisible.value = true
}

async function handleDialogConfirm() {
  const name = inputName.value.trim()
  if (!name) {
    ElMessage.warning('标签名称不能为空')
    return
  }

  try {
    if (isEditing.value && currentEditingTag.value) {
      const res = await updateTagRequest({
        id: currentEditingTag.value.id,
        name
      })
      if (res.code === 0) {
        ElMessage.success('标签修改成功')
      } else {
        ElMessage.error(res.message || '修改失败')
      }
    } else {
      const res = await createTagRequest({ name })
      if (res.code === 0) {
        ElMessage.success('标签添加成功')
      } else {
        ElMessage.error(res.message || '添加失败')
      }
    }

    await loadTags()
    dialogVisible.value = false
    isEditing.value = false
    currentEditingTag.value = null
    inputName.value = ''
  } catch {
    ElMessage.error('请求失败，请稍后重试')
  }
}

function confirmDelete(tag: Tag) {
  ElMessageBox.confirm(`确认删除标签「${tag.name}」？`, '提示', {
    confirmButtonText: '删除',
    cancelButtonText: '取消',
    type: 'warning'
  }).then(() => deleteTag(tag))
}

async function deleteTag(tag: Tag) {
  try {
    const res = await deleteTagRequest(tag.id)
    if (res.code === 0) {
      ElMessage.success('标签删除成功')
      await loadTags()
    } else {
      ElMessage.error(res.message || '删除失败')
    }
  } catch {
    // ElMessage.error('请求删除标签失败')
  }
}
</script>

<style scoped>
.mt-4 {
  margin-top: 16px;
}
</style>
